package com.next

import grails.converters.JSON
import grails.gorm.transactions.Transactional
import org.apache.commons.lang.StringUtils
import org.springframework.security.access.annotation.Secured

import java.text.SimpleDateFormat

import static org.springframework.http.HttpStatus.*

@Secured(['ROLE_ADMINISTRATOR', 'ROLE_HEAD_OFFICE_ADMINISTRATOR', 'ROLE_PROVINCE_BRANCH_OFFICE_ADMINISTRATOR', 'ROLE_PROVINCE_BRANCH_OFFICE_PRODUCT_MANAGER', 'ROLE_SECOND_BRANCH_OFFICE_PRODUCT_MANAGER',
    'ROLE_SECOND_BRANCH_OFFICE_DIRECTOR', 'ROLE_ACCOUNT_MANAGER', 'ROLE_SALES_REPRESENTATIVE', 'ROLE_BANK_OUTLETS_ADMINISTRATOR', 'ROLE_MERCHANT_ADMINISTRATOR', 'ROLE_CHANNEL_ADMINISTRATOR'])
@Transactional(readOnly = true)
class BocOpportunityController
{
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
    def billsService
    def opportunityService
    def contactservice
    def springSecurityService
    def assetValueService
    def opportunityNotificationService
    def creditReportService
    def contactService
    def opportunityStatisticsService
    def componentService
    def foticAheadService
    def avicAheadSubmitService

    @Transactional
    def show(Opportunity opportunity)
    {
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)

        def opportunityTeams = OpportunityTeam.findAllByOpportunity(opportunity)
        def opportunityFlows = WorkflowInstance.findAll("from WorkflowInstance where opportunity.id = ${opportunity?.id}")
        def opportunityContacts = OpportunityContact.findAllByOpportunity(opportunity)
        def opportunityBankAccounts = OpportunityBankAccount.findAllByOpportunity(opportunity)
        def houses = House.findAllByOpportunity(opportunity)
        def questionnaireInstance = QuestionnaireInstance.findByOpportunity(opportunity)
        def opportunityFlexFieldCategorys = OpportunityFlexFieldCategory.findAllByOpportunity(opportunity)

        //layout
        def instanceStageId = params['instanceStage']
        def instanceStage = WorkflowInstanceStage.findById(instanceStageId)
        def currentWorkflowInstance
        if (instanceStage)
        {
            currentWorkflowInstance = instanceStage?.instance
        }
        else if (opportunityFlows?.size() == 1)
        {
            currentWorkflowInstance = opportunityFlows[0]
        }

        def opportunityLayout
        if (!opportunityLayout)
        {
            if (instanceStage)
            {
                opportunityLayout = instanceStage?.desktopLayout?.name
            }
            else
            {
                opportunityFlows?.each {
                    if (it?.status == WorkflowInstanceStatus.findByName('Pending'))
                    {
                        opportunityLayout = it?.stage?.desktopLayout?.name
                    }
                }
            }

            opportunityTeams?.each {
                if (it?.user == user && it?.opportunityLayout)
                {
                    opportunityLayout = it?.opportunityLayout?.name
                }
            }
        }
        if (opportunityLayout)
        {
            respond opportunity, model: [opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys,
                opportunityContacts: opportunityContacts, opportunityBankAccounts: opportunityBankAccounts, houses: houses, questionnaireInstance: questionnaireInstance,
                user: user, currentWorkflowInstance: currentWorkflowInstance], view: opportunityLayout
        }
        else
        {
            respond opportunity, model: [opportunityTeams: opportunityTeams, opportunityFlows: opportunityFlows, opportunityFlexFieldCategorys: opportunityFlexFieldCategorys,
                opportunityContacts: opportunityContacts, opportunityBankAccounts: opportunityBankAccounts, houses: houses, questionnaireInstance: questionnaireInstance,
                user: user, currentWorkflowInstance: currentWorkflowInstance]
        }
    }

    def edit(Opportunity opportunity)
    {
        def flag = params['flag']
        def username = springSecurityService.getPrincipal().username
        def user = User.findByUsername(username)
        if (UserRole.findByUserAndRole(user, Role.findByAuthority("ROLE_ADMINISTRATOR")))
        {
            respond opportunity, view: 'administratorEdit'
        }
        else if (opportunity?.status == "Pending")
        {

            def stage = opportunity?.stage
            def opportunityRole = WorkflowInstanceUser.find("from WorkflowInstanceUser where stage.instance.opportunity.id = ${opportunity.id} and user.id = ${user.id} and stage.id = stage.instance.stage.id")

            if (opportunityRole && opportunityRole?.authority?.name != "Read")
            {
                respond opportunity, model: [flag: flag]
            }
            else
            {
                flash.message = message(code: 'opportunity.edit.permission.denied')
                redirect(controller: "opportunity", action: "show", params: [id: opportunity.id, flag: flag])
                return
            }
        }
        else
        {
            flash.message = message(code: 'opportunity.edit.permission.denied')
            redirect(controller: "opportunity", action: "show", params: [id: opportunity.id])
            return
        }
    }

    @Transactional
    def update(Opportunity opportunity)
    {
        if (opportunity == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (opportunity.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond opportunity.errors, view: 'edit'
            return
        }
        if (params["actuaDate"])
        {
            opportunity.actuaRepaymentDate = new SimpleDateFormat("yyyy-MM-dd").parse(params["actuaDate"])
            if (opportunity.parent)
            {
                opportunity.parent.actuaRepaymentDate = opportunity?.actuaRepaymentDate
                opportunity.parent.save flush: true
            }
        }
        if (opportunity.notarizations)
        {
            def last = opportunity.notarizations.substring(opportunity.notarizations.length() - 1, opportunity.notarizations.length())
            if (last == ",")
            {
                opportunity.notarizations = opportunity.notarizations.substring(0, opportunity.notarizations.lastIndexOf(","))
            }
        }
        def pro = ProductAccount.findByAccountAndProduct(opportunity?.account, opportunity?.product)
        opportunity.productAccount = pro
        def username = springSecurityService.getPrincipal().username
        opportunity.modifiedBy = User.findByUsername(username)
        opportunity.modifiedDate = new Date()
        /*//修改页面金额单位为万元
        opportunity.actualLoanAmount = opportunity?.actualLoanAmount * 10000
        opportunity.actualAmountOfCredit = opportunity?.actualAmountOfCredit * 10000
        opportunity.loanAmount = opportunity?.loanAmount * 10000
        opportunity.requestedAmount = opportunity?.requestedAmount * 10000
        opportunity.commission = opportunity?.commission * 10000
        opportunity.maximumAmountOfCredit = opportunity?.maximumAmountOfCredit * 10000*/
        opportunityService.backup(opportunity)

        opportunity.save flush: true
        redirect(controller: "opportunity", action: "show", id: opportunity.id)
    }

}
